import { HttpClient } from '@angular/common/http';
import { Component, EventEmitter, Inject, Input, OnChanges, OnInit, Optional, Output, SimpleChanges } from '@angular/core';
import { FormArray, FormControl, FormGroup, Validators } from '@angular/forms';
import { MonkFormDesign } from '../../monk-form-design.interface';
import * as Http from '@angular/common/http';
import * as rxjs from 'rxjs';
import * as operators from 'rxjs/operators';
import { MonkPreviewFormDesignConfig, MONK_PREVIEW_FORMDEISGN_CONFIG } from '../preview-form-design.interface';
import { NzFormTooltipIcon } from 'ng-zorro-antd/form';
import { DesignFormBuildComponent } from '../design-form-build/design-form-build.component';

@Component({
  selector: 'app-design-form-item',
  templateUrl: './design-form-item.component.html',
  styleUrls: ['./design-form-item.component.scss']
})
export class DesignFormItemComponent implements OnChanges, OnInit {
  infinity = Infinity
  captchaTooltipIcon: NzFormTooltipIcon = {
    type: 'info-circle',
    theme: 'twotone'
  };
  //@Input() key //="record.key"
  //:selectItem.sync="selectItem"

  @Input() record: MonkFormDesign.AllType //="record"
  @Input() formConfig //="record"
  @Input() disabledKeys?: any[] = []
  @Input() form: FormGroup  //??
  @Output() readonly previewOutput: EventEmitter<any> = new EventEmitter();
  @Input() readonly readonly = true

  @Input() desenColumn? = '' //脱敏字段 用,分割
  @Input() viewDesenInfo? = false //是否可查看脱敏信息 

  get layoutConfig() {
    return (this.record as any).options?.overrideLayout ? (this.record as any).options : this.formConfig;
  }
  constructor(
    @Optional() @Inject(MONK_PREVIEW_FORMDEISGN_CONFIG) private config: MonkPreviewFormDesignConfig,
    @Optional() private _DesignFormBuildComponent: DesignFormBuildComponent,
    private httpClient: HttpClient,
  ) {
    setTimeout(() => { console.log(this.desenColumn, this.viewDesenInfo, '-==-=-=-=-=-=-='); }, 2000)
  }

  get isCol() {
    return this.formConfig.layout === 'horizontal' && this.formConfig.labelLayout !== 'flex'
  }
  get isFlex() {
    return this.formConfig.layout === 'horizontal' && this.formConfig.labelLayout === 'flex'
  }

  get required() {
    return this.record['rules'] && this.record['rules'][0] && this.record['rules'][0]['required'] === true
  }

  get isDisabled() {

    let key = this.record.key.split(`.property[?(@.name=='`)[this.record.key.split(`.property[?(@.name=='`).length - 1].split(`')].content`)[0];
    return this.disabledKeys.includes(key);
  }

  ngOnInit(): void {
    if (this.record.type == 'select'
      || this.record.type == 'checkbox' || this.record.type == 'radio') {
      if (this.record.options.dynamicKey && this.config && this.config[this.record.options.dynamicEvalFuncToken]) {
        this.getOptionsByEvalFunc(this.config[this.record.options.dynamicEvalFuncToken])
      } else if (this.record.options.dynamicKey && this.config && this.config[this.record.options.dynamicInjectFuncToken]) {
        this.getOptionsByInjectFunc(this.config[this.record.options.dynamicInjectFuncToken]);
      }
    }


  }
  ngOnChanges(changes: SimpleChanges): void {
    if (!this.form && this.record && this.record.key) {
      this.form = new FormGroup({
        [this.record.key]: new FormControl()
      })
    }
  }

  async getOptionsByEvalFunc(dynamicEvalFuncToken) {
    const func = new Function(...dynamicEvalFuncToken)
    //['http', 'rxjs', 'httpClient',
    const result = await func({ http: Http, record: this.record, rxjs, operators, httpClient: this.httpClient });
    (this.record as MonkFormDesign.SelectType | MonkFormDesign.RadioType | MonkFormDesign.CheckboxType)
      .options.options = result.data;
  }

  async getOptionsByInjectFunc(func) {
    const result = await func({ record: this.record });
    (this.record as MonkFormDesign.SelectType | MonkFormDesign.RadioType | MonkFormDesign.CheckboxType)
      .options.options = result.data;
  }

  log(e) {
    console.log(e)
    return e
  }

  clearValue() {
    this.form.get(this.record.key).setValue(null)
  }

  getValue() {
    return this.form.get(this.record.key).value||null
  }

  getValueByKey(key) {
    return this.form.value?.[key]||null
  }

  valueLengthGtZero() {
    const value = this.getValue()
    return value && value.length
  }

  buttonClick() {
    const record = this.record as MonkFormDesign.ButtonType
    if (record.options.handle == 'dynamic') {
      try {
        eval(record.options.dynamicFun)
      } catch (e) {
        console.error(e)
      }
    } else { }
  }


  /**
   * 检查数据是否是敏感字段
  */
  isSensitive(columnName) {
    return this.desenColumn && this.getSensitiveField && this.getSensitiveField.some(e => { return columnName.includes(e) })
  }

  //数据脱敏 获取 敏感字段名称
  get getSensitiveField() {
    let lists = this.desenColumn || ""
    return lists.split(',')
  }
}